package com.android.support.lib.universal.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.android.support.lib.universal.base.BaseApplication;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.IWXAPI;

/**
 * 启动应用和卸载应用 使用： 直接实例化一个对象，调用里面的方法即可。
 *
 * @author 彭治铭
 */
public class Utilapk {
    private Intent intent;
    private Context context = BaseApplication.getInstance();

    /**
     * 启动应用
     *
     * @param apply 包名
     */
    public void getStart(String apply) throws Exception {
        intent = context.getPackageManager().getLaunchIntentForPackage(apply);
        context.startActivity(intent);
    }

    /**
     * 卸载应用
     *
     * @param apply 包名
     */
    public void getUnload(String apply) throws Exception {
        Uri packageURI = Uri.parse("package:" + apply);// xx是包名
        intent = new Intent(Intent.ACTION_DELETE, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 安装应用
     *
     * @param apk app的完整路径
     */
    public void getExe(File apk) {
        String path = apk.getAbsolutePath();
        if (getUninatllApkInfo(path)) {
            /* apk安装界面跳转 */
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(apk),
                    "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "安装包解析错误", Toast.LENGTH_LONG).show();
            // 删除安装包
            Utilfile utilFile = new Utilfile();
            utilFile.delFile(apk.getAbsolutePath(), null, null);
            utilFile = null;
        }
    }

    /**
     * 方法一 判断apk是否安装
     *
     * @param uri apk的包名
     * @return
     */
    public boolean isAppInstalled(String uri) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    /**
     * 方法二 判断apk是否安装
     *
     * @param packageName apk的包名
     * @return
     */
    public boolean isAppInstalleds(String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

    /**
     * 判断微信是否安装 IWXAPI api = WXAPIFactory.createWXAPI(this,
     * WXEntryActivity.APPID, true);
     * if(UtilApp.isWXAppInstalledAndSupported(api)){//判断是否安装微信 }
     *
     * @param api
     * @return
     */
    public boolean isWXAppInstalledAndSupported(IWXAPI api) {
        // LogOutput.d(TAG, "isWXAppInstalledAndSupported");
        Boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            try {
                Utilview.showToastView("请先安装微信！");
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("test", "utilapk.java 134报错:" + e.getMessage());
            }

        }

        return sIsWXAppInstalledAndSupported;
    }

    /**
     * 获取apK包名
     *
     * @param apk 安装包的完整路径
     * @return
     */
    public String getPackageName(String apk) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apk,
                PackageManager.GET_ACTIVITIES);
        ApplicationInfo appInfo = null;
        if (info != null) {
            appInfo = info.applicationInfo;
            return appInfo.packageName;
        }
        return null;
    }

    /**
     * 判断apk安装包是否完整
     *
     * @param filePath
     * @return
     */
    public boolean getUninatllApkInfo(String filePath) {
        boolean result = false;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(filePath,
                    PackageManager.GET_ACTIVITIES);
            String packageName = null;
            if (info != null) {
                result = true;
            }
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    /**
     * 获取版本信息 versionName
     *
     * @return
     */
    public String getVersion() {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本号 versionCode
     *
     * @return
     */
    public int getVersionNo() {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            return packInfo.versionCode;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取Android SDK的版本号
     *
     * @return
     */
    public static int getAndroidOSVersion() {
        int osVersion;
        try {
            osVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            osVersion = 0;
        }
        return osVersion;
    }

    /**
     * 获取application中指定的meta-data (渠道号)，如(写在清单里，与Activity一样)<meta-data android:name="PUSH_APPID" android:value="1Y1Zt2hJmV5rHGdLRg0Ya" /> 
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public String getAppMetaData(String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager
                        .getApplicationInfo(context.getPackageName(),
                                PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }
}
